

from django.conf import settings
#from django.db.models import get_app

COVERAGE_TEST_RUNNER = "django_contract.coverage_test_runner.test_runner_with_coverage"

class ContractConfigurationError(Exception):
    pass


def contract_enable():
    try:
        contract_modules_iterator = getattr(settings, "CONTRACT_MODULES", None).iteritems()
    except AttributeError:
        raise ContractConfigurationError("settings.CONTRACT_MODULES must be a dictionary.")
    
    contract_check_level = getattr(settings, "CONTRACT_CHECK_LEVEL", "CHECK_ALL")
    if not contract_check_level in ("CHECK_DEFAULT", "CHECK_NONE", "CHECK_PRECONDITIONS", "CHECK_ALL"):
        raise ContractConfigurationError("Invalid settings.CONTRACT_CHECK_LEVEL")
    
    from django_contract import contract
    
    if getattr(settings, "CONTRACT_CHECK_INHERITED", True):
        # Enable patched contract.py
        contract.CHECK_INHERITED = True
    
    def dynamic_import(name, attrs):
        mod = __import__(name, {}, {}, attrs)
        components = name.split(".")
        for comp in components[1:]:
            mod = getattr(mod, comp)
        return mod
    
    for app, attrs in contract_modules_iterator:
#        contract.checkmod(get_app(app), checklevel=getattr(contract, contract_check_level))
        mod = dynamic_import(app, attrs)
        contract.checkmod(mod, checklevel=getattr(contract, contract_check_level))
        for attr in attrs:
            contract.checkmod(getattr(mod, attr), checklevel=getattr(contract, contract_check_level))
        
if (getattr(settings, "CONTRACT_ENABLE", False)
    and getattr(settings, "TEST_RUNNER", "") != COVERAGE_TEST_RUNNER):
    # when the coverage test runner is used contract_enabling has
    # to be postponed because of some weird problems. It is enabled
    # in the testrunner.
    contract_enable()

